cc.Class({
    extends: cc.Button,

    properties: {
        longClickEvents: {
            tooltip: '长按触发的事件',
            default: [],
            type: cc.Component.EventHandler,
        },
        cancelLongClickEvents: {
            tooltip: '取消长按触发的事件',
            default: [],
            type: cc.Component.EventHandler,
        },
        interval: {
            tooltip: '长按时间',
            default: 1,
            range: [0, 10],
        }
    },

    _mTouchStartTime: null,

    _onTouchBegan() {
        if (!this.interactable || !this.enabledInHierarchy) return;
        this._super(event);
        this._mTouchStartTime = Date.now();
        this.scheduleOnce(() => {
            this._onLongTouch(event);
        }, this.interval);
    },
    _onTouchEnded(event) {
        if (!this.interactable || !this.enabledInHierarchy) return;
        cc.director.getScheduler().unscheduleAllForTarget(this);
        if (Date.now() - this._mTouchStartTime >= this.interval * 1000) {
            this._onCancelLongTouch(event);
        } else {
            this._super(event);
        }
    },
    _onTouchCancel() {
        if (!this.interactable || !this.enabledInHierarchy) return;
        cc.director.getScheduler().unscheduleAllForTarget(this);
        this._onCancelLongTouch(event);
    },

    _onLongTouch(event) {
        if (!this.interactable || !this.enabledInHierarchy) return;

        if (this._pressed) {
            cc.Component.EventHandler.emitEvents(this.longClickEvents, event);
        }
    },
    _onCancelLongTouch(event) {
        if (!this.interactable || !this.enabledInHierarchy) return;

        if (this._pressed) {
            cc.Component.EventHandler.emitEvents(this.cancelLongClickEvents, event);
            this.node.emit('click', this);
        }
        this._pressed = false;
        this._updateState();
        event.stopPropagation();
    },
});
